//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 赵志文 on 15/11/22.
//  Copyright © 2015年 zzw. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", style: UIBarButtonItemStyle.Plain, target: self, action: "autoLogIn")
    }
    
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充用户信息
    @objc private func autoLogIn(){
        let js = "document.getElementById('userId').value = '1041571024@qq.com';" +
        "document.getElementById('passwd').value = '5783496z,';"
        
        // 执行 js 脚本
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        webView.loadRequest(NSURLRequest(URL: NetWorkTools.sharedTools.oauthUrl))
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix(NetWorkTools.sharedTools.redirectUri){
            return true
        }
        
        if let quer = request.URL!.query where quer.hasPrefix("code="){
            let code = quer.substringFromIndex("code=".endIndex)
            
            NetWorkTools.sharedTools.loadAccessToken(code) .subscribeNext({ (result) -> Void in
//                print(result)
                let acount = UserAccount(dict: result as! [String : AnyObject])
                printLog(acount)
                //获取用户信息
                self.loadUserInfo(acount)
                
                }, error: { (error) -> Void in
                    print(error)
            })
        }
       
        return true
    }
    
    private func loadUserInfo(user:UserAccount){
        NetWorkTools.sharedTools.loadUserInfo(user.uid!, accesToken: user.access_token!) .subscribeNext({ (result) -> Void in
            let dict = result as![String:AnyObject]
            user.name = dict["name"] as?String
            user.avatar_large = dict["avatar_large"] as?String
            }, error: { (error) -> Void in
                printLog(error)
            }) { () -> Void in
                
        }
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    

}
